package com.woniuxy.usercoachassemble.controller;


import com.alibaba.fastjson.JSON;
import com.woniuxy.usercoachassemble.entity.Inform;
import com.woniuxy.usercoachassemble.service.InformService;
import com.woniuxy.usercoachassemble.webservice.WebSocketServer;
import org.example.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Lucas
 * @since 2020-07-21
 */
@RestController
@RequestMapping("inform")
public class InformController {

    @Autowired
    private InformService informService;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * @description:TODO(发送通知)
     * @param readId 接受人id
     * @param writeId 发送人id
     * @param message 发送的消息
     * @param type 消息类型id
     * @return:
     * @author: Fy浪迹、
     * @date: 2020/7/21 2:32
     */

    @PostMapping("insertInform")
    public Result insertInform(Integer readId, Integer writeId, String message, Integer type) throws IOException {
        Inform inform = new Inform();
        inform.setReadId(readId);
        inform.setWriteId(writeId);
        inform.setMessage(message);
        inform.setType(type);
        inform.setStatus(1);
        inform.setTime(LocalDateTime.now());


        // websoct发送消息
        webSocketServer.sendInfo(JSON.toJSONString(inform),readId + "");
        informService.save(inform);
        return Result.Success(inform);
    }


    // 读未读通知
    @PostMapping("readInfom")
    public Result readInfom(HttpServletRequest request){
        int userId = Integer.parseInt(request.getHeader("userId"));
        informService.update().set("status",2).eq("status",1).eq("read_id",userId).update();
        return  Result.Success();
    }

    // 查询未读通知
    @GetMapping("selectUnreadInfom")
    public Result selectUnreadInfom(HttpServletRequest request){
        int userId = Integer.parseInt(request.getHeader("userId"));
        List<Inform> list = informService.query().eq("status", 1).eq("read_id", userId).list();
        return Result.Success(list);
    }

    // 查询所有通知
    @GetMapping("selectAllInfom")
    public Result selectAllInfom(HttpServletRequest request){
        int userId = Integer.parseInt(request.getHeader("userId"));
        List<Inform> list = informService.query().eq("read_id", userId).list();
        return Result.Success(list);
    }




}

